package server.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import server.Server;
import server.Session;

/**
 * This class is the network end of the server.
 * Each client must connect to at instance of this class
 * to update/save/get information from/to the database.
 * @author daniel
 * @author Erik
 */
public class ServerTCP implements Runnable {

	private boolean run = true;
	
	private ServerSocket socket;

	/**
	 * Establishes the server over a specific port.
	 */
	public ServerTCP(int port) {
		try {
			socket = new ServerSocket(port);
			start();
//			System.out.println("ServerTCP::Constructor: Server socket started");
		} catch (Exception e) {
//			System.out.println("ServerTCP::Constructor: Server socket failed to start");
			e.printStackTrace();
		}
	}
	
	/**
	 * Receives the connection from different clients,
	 * and establishes a new socket connection for each
	 * one. Then each socket is wrapped around a session,
	 * and the session added to the {@link SessionHandler}
	 */
	public void start() {
		Thread thread = new Thread(this);
		thread.start();
	}
	
	/**
	 * Receives the connection from different clients,
	 * and establishes a new socket connection for each
	 * one. Then each socket is wrapped around a session,
	 * and the session added to the {@link SessionHandler}
	 */
	@Override
	public void run() {
		while(run) {
			try {
				if(socket != null && !socket.isClosed()) {
					Socket incoming;
				incoming = socket.accept();
				Session session = new Session(incoming);	
				Server.addSession(session);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * Forces the server to close all connections
	 */
	public void forceEnd() {
		try {
			if(socket != null && !socket.isClosed()) {
				socket.close();
			}
		} catch (IOException e) {
			//e.printStackTrace();
		}
	}

}
